<template>
  <fs-page>
    <template #header>
      <div class="title">
        角色管理
        <fs-icon icon="carbon:user-role" :spin="true" />
      </div>
    </template>
    <fs-crud ref="crudRef" v-bind="crudBinding">
      <template #form_orgList="scope">
        <n-tree
          block-line
          cascade
          checkable
          default-expand-all
          :show-irrelevant-nodes="false"
          :virtual-scroll="true"
          :pattern="pattern"
          :key-field="`id`"
          :data="treeData"
          v-model:checked-keys="scope.form.orgList"
          v-if="scope.form.scopeType === 20"
        />
      </template>
      <template #cell_description="scope">
        <n-tooltip placement="bottom" trigger="hover">
          <template #trigger>
            {{ scope.row.description }}
          </template>
          <span> {{ scope.row.description }} </span>
        </n-tooltip>
      </template>
    </fs-crud>

    <basicModal @register="registerBindUser" class="basicModal" @on-ok="handleSubmit">
      <template #default>
        <n-transfer
          ref="transfer"
          :source-title="`用户列表`"
          :target-title="`绑定用户`"
          v-model:value="targetKeys"
          virtual-scroll
          :options="userRoleDetails"
          filterable
          size="large"
        />
      </template>
    </basicModal>

    <n-drawer v-model:show="active" :width="800">
      <n-drawer-content closable>
        <template #header> 分配权限 </template>
        <template #footer>
          <n-button type="primary" @click="handleResSubmit">确定</n-button>
        </template>
        <n-grid class="mt-3" cols="1 s:1 m:1 l:3 xl:3 2xl:3" responsive="screen" :x-gap="12">
          <n-gi span="1">
            <n-card :segmented="{ content: true }" :bordered="false" size="small">
              <div class="w-full menu">
                <n-input type="input" v-model:value="pattern" placeholder="输入菜单名称搜索">
                  <template #suffix>
                    <n-icon size="18" class="cursor-pointer">
                      <SearchOutlined />
                    </n-icon>
                  </template>
                </n-input>
                <div class="py-3 menu-list">
                  <template v-if="loading">
                    <div class="flex items-center justify-center py-4">
                      <n-spin size="medium" />
                    </div>
                  </template>
                  <template v-else>
                    <n-tree
                      block-line
                      cascade
                      checkable
                      default-expand-all
                      :show-irrelevant-nodes="false"
                      :virtual-scroll="true"
                      :pattern="pattern"
                      :key-field="`id`"
                      :data="permissionTreeData"
                      :checked-keys="checkedKeys"
                      @update:checked-keys="checkKeys"
                      @update:selected-keys="selectedKeys"
                    />
                  </template>
                </div>
              </div>
            </n-card>
          </n-gi>
          <n-gi span="2">
            <n-card :segmented="{ content: true }" :bordered="false" size="small">
              <BasicTable
                title="权限标识"
                titleTooltip="提示"
                :columns="columns"
                :dataSource="tableData"
                :row-key="(row) => row.id"
                v-model:checked-row-keys="buttonIdList"
                ref="actionRef"
              />
            </n-card>
          </n-gi>
        </n-grid>
      </n-drawer-content>
    </n-drawer>
  </fs-page>
</template>

<script>
  import { defineComponent, ref, onMounted } from 'vue';
  import createCrudOptions from './crud';
  import { useExpose, useCrud } from '@fast-crud/fast-crud';
  import { request } from '@/utils/http/service';
  import { basicModal, useModal } from '@/components/Modal';
  import { BasicTable } from '@/components/Table';
  import * as api from './api';
  import { SearchOutlined } from '@vicons/antd';
  import { getMenuList, GetPermissionList } from '@/api/system/menu';

  function useDistribution() {
    const modelRef = ref({
      roleId: '',
      userRoleDetails: [],
      originTargetKeys: [],
    });
    const userRoleDetails = ref([]);
    const targetKeys = ref([]);

    const active = ref(false);
    const pattern = ref('');
    const loading = ref(true);
    const permissionTreeData = ref();
    const checkedKeys = ref([]);
    const roleIdRef = ref();

    const buttonIdList = ref([...new Set()]);

    const actionRef = ref();
    const tableData = ref([]);
    const columns = [
      {
        type: 'selection',
      },
      {
        title: '权限标识码',
        key: 'permission',
        width: 100,
      },
      {
        title: '权限名称',
        key: 'label',
        width: 100,
      },
    ];

    function userModal(roleId) {
      api.GetUserByRoleId(roleId).then(({ data }) => {
        modelRef.value = {
          roleId: roleId,
          userRoleDetails: data.userRoleDetails,
          originTargetKeys: data.originTargetKeys,
        };
        userRoleDetails.value = data.userRoleDetails?.map((item) => {
          return { value: String(item.id), label: item.nickName, ...item };
        });
        targetKeys.value = data.originTargetKeys?.map((key) => key.toString());
        openUserModal();
      });
    }

    function handleSubmit() {
      api.DistributionUser({ roleId: modelRef.value.roleId, userIdList: targetKeys.value });
      closeUserModal();
    }

    const [registerBindUser, { openModal: openUserModal, closeModal: closeUserModal }] = useModal({
      title: '分配用户',
    });

    async function resourceDrawer(roleId) {
      active.value = true;
      roleIdRef.value = roleId;
      await getMenuList().then((ret) => {
        permissionTreeData.value = ret;
      });
      await GetPermissionList(roleId).then((data) => {
        checkedKeys.value = data.buttons
          ?.filter((item) => !(item.type === 2))
          .filter((item) => data.resIdList.includes(item.id))
          .map((item) => item.id);
        buttonIdList.value = data.buttons
          ?.filter((item) => item.type === 2)
          .filter((item) => data.resIdList.includes(item.id))
          .map((item) => item.id);
      });
      loading.value = false;
    }

    function checkKeys(keys) {
      checkedKeys.value = keys;
    }

    async function selectedKeys(keys) {
      const { data } = await api.GetResourceList({ parentId: keys[0] || '-999999', type: '2' });
      tableData.value = data.records;
    }

    function handleResSubmit() {
      const data = [...new Set(buttonIdList.value.concat(checkedKeys.value))];
      api.DistributionRoleAuthority({ roleId: roleIdRef.value, resIds: data }).then(() => {
        window['$message'].success('权限分配成功');
        active.value = false;
      });
    }

    return {
      modelRef,
      userRoleDetails,
      targetKeys,
      active,
      pattern,
      loading,
      permissionTreeData,
      checkedKeys,
      buttonIdList,
      actionRef,
      tableData,
      columns,

      registerBindUser,
      userModal,
      handleSubmit,

      resourceDrawer,
      checkKeys,
      selectedKeys,
      handleResSubmit,
    };
  }

  export default defineComponent({
    name: 'SlotsForm',
    components: { basicModal, BasicTable, SearchOutlined },
    setup() {
      // crud组件的ref
      const crudRef = ref();
      // crud 配置的ref
      const crudBinding = ref();

      const distribution = useDistribution();
      // 暴露的方法
      const { expose } = useExpose({ crudRef, crudBinding });

      // const go = useGo();
      // 你的crud配置
      const { crudOptions } = createCrudOptions({ expose, distribution });
      // 初始化crud配置
      useCrud({ expose, crudOptions, permission: 'role:management' });

      const treeData = ref([]);
      function initOrgList() {
        request({
          url: '/authority/org/trees',
          method: 'get',
          params: { status: true },
        }).then((response) => {
          treeData.value = response.data;
        });
      }

      onMounted(() => {
        initOrgList();
        expose.doRefresh();
      });

      return {
        treeData,
        crudBinding,
        crudRef,
        ...distribution,
      };
    },
  });
</script>

<style lang="less">
  .basicForm {
    padding-top: 20px;
  }

  .n-transfer {
    width: auto;
    height: 500px;
  }

  .n-dialog.basicModal {
    width: 840px;
  }

  .n-dialog-content {
    height: 640px;
  }

  .n-dialog.basicModalLight {
    width: 516px;
    padding-top: 26px;
  }
</style>
